﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Data;

public partial class admin_DocumentDetail : SitePage
{
    #region Fields
    public string Command
    {

        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["Command"] = value; }

    }
    public string FileName
    {

        get
        {
            object o = ViewState["FileName"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["FileName"] = value; }

    }
   
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadData();
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();
    }
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

    }
    #endregion

    #region Methods
    private void LoadData()
    {
        clsSQL sql = new clsSQL();
        //Color
        DataTable dt = sql.ExecDataTable("SELECT DISTINCT Color FROM Document ORDER BY Color ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpColor.DataSource = dt;
            drpColor.DataTextField = "Color";
            drpColor.DataValueField = "Color";
            drpColor.DataBind();
        }

        //Size
        dt = sql.ExecDataTable("SELECT DISTINCT Size FROM Document ORDER BY Size ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpSize.DataSource = dt;
            drpSize.DataTextField = "Size";
            drpSize.DataValueField = "Size";
            drpSize.DataBind();
        }

        //Material
        dt = sql.ExecDataTable("SELECT DISTINCT Material FROM Document ORDER BY Material ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpMaterial.DataSource = dt;
            drpMaterial.DataTextField = "Material";
            drpMaterial.DataValueField = "Material";
            drpMaterial.DataBind();
        }

        dt.Dispose();

        if (clsCheck.QueryString("F_txtSKU", enmDataType._String))
        {
            txtSKU.Text = clsString.QueryString("F_txtSKU");
        }

        if (this.Command == "edit")
        {
            int documentID = clsQueryString.GetInt("id");
            busDocument objBus = new busDocument();
            Document objDocument = objBus.GetByID(documentID);
            if (objDocument != null)
            {
                txtName.Text = objDocument.Name;
                txtSize.Text = objDocument.Size;
                txtColor.Text = objDocument.Color;
                txtMaterial.Text = objDocument.Material;

                drpSize.SelectedValue = objDocument.Size;
                drpColor.SelectedValue = objDocument.Color;
                drpMaterial.SelectedValue = objDocument.Material;

                if (objDocument.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
                this.FileName = objDocument.FileName;
                hidFile.Value = objDocument.FileName;
                string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_FOLDER);
                if (File.Exists(fullPath + objDocument.FileName))
                {
                    ltrPath.Text = "<a href='" + this.ApplicationRoot + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_FOLDER + objDocument.FileName + "'>" + objDocument.FileName + "</a>";
                    trPath.Visible = true;
                }

                //get Product SKU
                busDocumentProduct busDocumentProduct=new busDocumentProduct();
                DocumentProductCollection lstProduct = busDocumentProduct.GetBydocumentID(documentID);
                if (lstProduct != null && lstProduct.Count > 0)
                {
                    txtSKU.Text = lstProduct[0].SKU;
                }

                
            }
        }
    }
    private void InitData()
    {
        string validateGroup = "msDSDetail";
        vsumMSDS.ValidationGroup = btnSave.ValidationGroup = reqName.ValidationGroup = cusFile.ValidationGroup=validateGroup;
        //Init message
        reqName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Name");        
        cusFile.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "File name");
        this.Command = clsQueryString.GetString("act");       
    }

    private void UpdateDocument(Document objDocument, bool bUpdateDocumentProduct)
    {
        busDocument objBus = new busDocument();
        if (objDocument.DocumentID < 0)
            objDocument.DocumentID = clsQueryString.GetInt("id");

        if (objBus.Update(objDocument))
        {
            if (bUpdateDocumentProduct)
            {
                //Insert DocumentProduct
                busDocumentProduct objBusDocumentProduct = new busDocumentProduct();
                DocumentProduct objDocumentProduct = new DocumentProduct();
                objDocumentProduct.SKU = txtSKU.Text;
                objDocumentProduct.DocumentID = objDocument.DocumentID;
                objBusDocumentProduct.Insert(objDocumentProduct);
            }
            Response.Redirect("DocumentList.aspx?" + this.GetPageQuery);
        }
        else lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
    }

    private int InsertDocument(Document objDocument)
    {
        busDocument objBus = new busDocument();
        int result = objBus.Insert(objDocument);
        if (result > 0 && txtSKU.Text.Length > 0)
        {
            //Insert DocumentProduct
            busDocumentProduct objBusDocumentProduct = new busDocumentProduct();
            DocumentProduct objDocumentProduct = new DocumentProduct();
            objDocumentProduct.SKU = txtSKU.Text;
            objDocumentProduct.DocumentID = result;
            objBusDocumentProduct.Insert(objDocumentProduct);
        }
        else
        {
            this.DeleteImage(objDocument.FileName);
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }

        return result;
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (txtSKU.Text != string.Empty)
            { 
                //checfk SKU is valid
                busProduct objBusProduct=new busProduct();
                Product objProduct = objBusProduct.GetBySKU(txtSKU.Text);
                if (objProduct == null)
                {
                    lblErrorMessage.Text = string.Format(Resources.Resource.MSG_INSERT_DOCUMENT_PRODUCT, txtSKU.Text);
                    return;
                }
            }

            //get datavalue
            Document objData = new Document();
            objData.CreatedBy = this.userloginName;
            objData.CreatedDate = clsDateTime.Now;
            objData.Name = txtName.Text.Trim();

            if (txtSize.Text.Trim().Length > 0)
            {
                objData.Size = txtSize.Text.Trim();
            }
            else if(drpSize.SelectedValue != "")
            {
                objData.Size = drpSize.SelectedValue;
            }
            else
            {
                objData.Size = string.Empty;
            }

            if (txtColor.Text.Trim().Length > 0)
            {
                objData.Color = txtColor.Text.Trim();
            }
            else if (drpColor.SelectedValue != "")
            {
                objData.Color = drpColor.SelectedValue;
            }
            else
            {
                objData.Color = string.Empty;
            }

            if (txtMaterial.Text.Trim().Length > 0)
            {
                objData.Material = txtMaterial.Text.Trim();
            }
            else if (drpMaterial.SelectedValue != "")
            {
                objData.Material = drpMaterial.SelectedValue;
            }
            else
            {
                objData.Material = string.Empty;
            }

            objData.IsActive = chkIsActive.Checked;
            objData.UpdatedBy = this.userloginName;
            objData.UpdatedDate = clsDateTime.Now;

            if (this.Command == "edit")
            {
                objData.FileName = hidFile.Value;
                UpdateDocument(objData, true);
            }
            else
            {
                objData.FileName = "";
                objData.DocumentID = InsertDocument(objData);
            }

            if (objData.DocumentID > 0)
            {
                objData.FileName = UploadImage(fulFile, objData.DocumentID.ToString());
                UpdateDocument(objData, false);
            }
            
        }
        else
        {
            vsumMSDS.ShowMessageBox = false;
            vsumMSDS.ShowSummary = true;
        }
    }

    private string UploadImage(FileUpload _ful, string fileName)
    {
        string newFullFileName = "";
        if (_ful.HasFile)
        {
            string fileNameUpload = _ful.FileName;
            string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
            newFullFileName = fileName + extFile;
            string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_FOLDER);//upload images           
            string pathResizeImages = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_IMAGES_FOLDER);
            string pathResizeThumb = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_THUMB_FOLDER);
            string pathResizeLarge = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_LARGE_FOLDER);
            string pathResizeSmall = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_SMALL_FOLDER);
            _ful.SaveAs(fullPath + newFullFileName);

            System.Drawing.Imaging.ImageFormat imgFormat = clsImage.GetImageFormat(extFile);
            using (System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(fullPath + newFullFileName))
            {
                System.Drawing.Image imgThumb = clsImage.ScaleCrop(imgPhoto, 58, 58, AnchorPosition.Center, true, false);
                imgThumb.Save(pathResizeThumb + newFullFileName, imgFormat);
                imgThumb.Dispose();

                System.Drawing.Image imgLarge = clsImage.ScaleCrop(imgPhoto, 640, 640, AnchorPosition.Center, true, false);
                imgLarge.Save(pathResizeLarge + newFullFileName, imgFormat);
                imgLarge.Dispose();
            }  

            // delete source image
            clsFile.DeleteFile(fullPath + newFullFileName);
        }
        return newFullFileName;
    }

    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_IMAGES_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_THUMB_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_DOCUMENT_LARGE_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("DocumentList.aspx?" + this.GetPageQuery);
    }
   
    
    #endregion

    #region Validate Data
    protected void CheckSDocumentValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
    }
    #endregion
}